package handler

import (
	"net/http"
	"os"
	"path/filepath"

	"github.com/gin-gonic/gin"
	"markedit/internal/database"
	"markedit/internal/middleware"
	"markedit/internal/service"
	"markedit/pkg/utils"
)

// RegisterRoutes 注册所有路由
func RegisterRoutes(router *gin.Engine) {
	// 初始化日志
	logger := utils.GetLogger()

	// 初始化数据目录
	dataDir := "./data"
	tempDir := "./temp"
	os.MkdirAll(dataDir, 0755)
	os.MkdirAll(tempDir, 0755)

	// 初始化服务
	configService := service.NewConfigService(filepath.Join(dataDir, "config.json"), logger)
	fileService := service.NewFileService(dataDir, logger)
	renderService := service.NewRenderService("http://www.plantuml.com/plantuml", logger, tempDir)
	markdownService := service.NewMarkdownService(logger, renderService)
	exportService := service.NewExportService(markdownService, renderService, logger, tempDir)
	
	// 用户系统服务
	db := database.GetDB()
	jwtSecret := "markedit_jwt_secret_key_2024" // 在生产环境中应该从配置文件读取
	userService := service.NewUserService(db, logger, jwtSecret)
	userFileService := service.NewUserFileService(db, logger)

	// 初始化处理器
	configHandler := NewConfigHandler(configService, logger)
	fileHandler := NewFileHandler(fileService, logger)
	renderHandler := NewRenderHandler(renderService, logger)
	markdownHandler := NewMarkdownHandler(markdownService, logger)
	exportHandler := NewExportHandler(exportService, fileService, logger)
	filesystemHandler := NewFileSystemHandler(logger)
	
	// 用户系统处理器
	userHandler := NewUserHandler(userService, logger)
	userFileHandler := NewUserFileHandler(userFileService, logger)

	// 健康检查
	router.GET("/health", healthCheck)

	// 测试路由
	router.GET("/test", func(c *gin.Context) {
		c.String(http.StatusOK, "Test route is working!")
	})

	// 主页
	router.GET("/", indexHandler)

	// API路由组
	api := router.Group("/api")
	{
		// 用户认证相关（无需登录）
		auth := api.Group("/auth")
		{
			auth.POST("/register", userHandler.Register)
			auth.POST("/login", userHandler.Login)
		}

		// 用户相关（需要登录）
		user := api.Group("/user")
		user.Use(middleware.AuthMiddleware(userService))
		{
			user.GET("/profile", userHandler.GetProfile)
			user.PUT("/profile", userHandler.UpdateProfile)
			user.POST("/change-password", userHandler.ChangePassword)
			user.POST("/logout", userHandler.Logout)
		}

		// 用户文件管理（需要登录）
		userFiles := api.Group("/user-files")
		userFiles.Use(middleware.AuthMiddleware(userService))
		{
			userFiles.POST("/", userFileHandler.CreateFile)
			userFiles.GET("/:id", userFileHandler.GetFile)
			userFiles.PUT("/:id", userFileHandler.UpdateFile)
			userFiles.DELETE("/:id", userFileHandler.DeleteFile)
			userFiles.POST("/:id/rename", userFileHandler.RenameFile)
			userFiles.GET("/", userFileHandler.ListFiles)
			userFiles.GET("/tree", userFileHandler.GetFileTree)
			userFiles.GET("/search", userFileHandler.SearchFiles)
			userFiles.POST("/save", userFileHandler.SaveFile) // 保存文件到账户空间
		}

		// 文件管理（保持兼容性，可选认证）
		files := api.Group("/files")
		files.Use(middleware.OptionalAuthMiddleware(userService))
		{
			files.POST("/documents", fileHandler.CreateDocument)
			files.GET("/documents/:id", fileHandler.GetDocument)
			files.PUT("/documents/:id", fileHandler.UpdateDocument)
			files.DELETE("/documents/:id", fileHandler.DeleteDocument)
			files.GET("/documents", fileHandler.ListDocuments)
			files.GET("/search", fileHandler.SearchDocuments)
			
			files.POST("/folders", fileHandler.CreateFolder)
			files.GET("/folders/:id", fileHandler.GetFolder)
			files.GET("/folders", fileHandler.ListFolders)
			files.DELETE("/folders/:id", fileHandler.DeleteFolder)
			
			files.POST("/upload", fileHandler.UploadFile)
		}

		// Markdown相关
		markdown := api.Group("/markdown")
		{
			markdown.POST("/parse", markdownHandler.ParseMarkdown)
			markdown.POST("/preview", markdownHandler.PreviewMarkdown)
			markdown.POST("/render", markdownHandler.RenderMarkdown)
		}

		// 导出相关
		export := api.Group("/export")
		{
			export.POST("/pdf", exportHandler.ExportToPDF)
			export.POST("/word", exportHandler.ExportToWord)
			export.POST("/html", exportHandler.ExportToHTML)
		}

		// 图片渲染相关
		render := api.Group("/render")
		{
			render.POST("/chart", renderHandler.RenderChart)
			render.POST("/mermaid", renderHandler.RenderMermaid)
			render.POST("/plantuml", renderHandler.RenderPlantUML)
			render.POST("/preview", renderHandler.PreviewImage)
			render.GET("/settings", renderHandler.GetRenderSettings)
			render.POST("/batch", renderHandler.BatchRender)
		}

		// 配置管理
		config := api.Group("/config")
		{
			config.GET("/", configHandler.GetConfig)
			config.POST("/", configHandler.UpdateConfig)
			config.GET("/all", configHandler.GetAllConfig)
			config.POST("/reset", configHandler.ResetConfig)
			config.GET("/export", configHandler.GetExportConfig)
		}

		// 文件系统管理
		filesystem := api.Group("/filesystem")
		{
			filesystem.GET("/tree", filesystemHandler.GetDirectoryTree)
			filesystem.GET("/file", filesystemHandler.ReadFile)
		}
	}
}

// healthCheck 健康检查
func healthCheck(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"status": "ok",
		"message": "MarkEdit服务运行正常",
	})
}

// indexHandler 主页处理器
func indexHandler(c *gin.Context) {
	c.HTML(http.StatusOK, "index.html", gin.H{
		"title": "MarkEdit - Markdown编辑器",
	})
}